<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable ref="proTable" :columns="columns" :request-api="getRouteListApi" :pagination="false" :row-key="'FId'">
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="CirclePlus" @click="openDrawer('add')">新增路由</el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('edit', scope.row)">编辑</el-button>
          <el-button type="primary" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </ProTable>
    </div>

    <!-- 新增/编辑抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" direction="rtl" size="40%" destroy-on-close>
      <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="父级路由" prop="FParentId">
          <el-tree-select
            v-model="formData.FParentId"
            :data="routeTreeData"
            check-strictly
            :props="{ label: 'FTitle', value: 'FId' }"
            placeholder="请选择父级路由"
            clearable
          />
        </el-form-item>
        <el-form-item label="路由标题" prop="FTitle">
          <el-input v-model="formData.FTitle" placeholder="请输入路由标题" />
        </el-form-item>
        <el-form-item label="路由名称" prop="FName">
          <el-input v-model="formData.FName" placeholder="请输入路由名称" />
        </el-form-item>
        <el-form-item label="路由路径" prop="FPath">
          <el-input v-model="formData.FPath" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="组件路径" prop="FComponent">
          <el-input v-model="formData.FComponent" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="重定向路径" prop="FRedirect">
          <el-input v-model="formData.FRedirect" placeholder="请输入重定向路径" />
        </el-form-item>
        <el-form-item label="图标" prop="FIcon">
          <el-input v-model="formData.FIcon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="外链地址" prop="FIsLink">
          <el-input v-model="formData.FIsLink" placeholder="请输入外链地址" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="FOrderNum">
          <el-input-number v-model="formData.FOrderNum" :min="0" />
        </el-form-item>
        <el-form-item label="是否隐藏" prop="FIsHide">
          <el-switch v-model="formData.FIsHide" />
        </el-form-item>
        <el-form-item label="是否全屏" prop="FIsFull">
          <el-switch v-model="formData.FIsFull" />
        </el-form-item>
        <el-form-item label="是否固定" prop="FIsAffix">
          <el-switch v-model="formData.FIsAffix" />
        </el-form-item>
        <el-form-item label="是否缓存" prop="FIsKeepAlive">
          <el-switch v-model="formData.FIsKeepAlive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="tsx" name="routeManagement">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Route } from "@/api/interface/route";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import { getRouteListApi, addRouteApi, updateRouteApi, deleteRouteApi } from "@/api/modules/route";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const formRef = ref();
const routeTreeData = ref<Route.RouteItem[]>([]);

// 抽屉控制
const drawerVisible = ref(false);
const drawerTitle = ref("");
const actionType = ref<"add" | "edit">("add");

// 表单数据
const formData = reactive<Route.RouteParams>({
  FParentId: null,
  FTitle: "",
  FName: "",
  FPath: "",
  FComponent: "",
  FRedirect: null,
  FIcon: "",
  FIsLink: "",
  FIsHide: false,
  FIsFull: false,
  FIsAffix: false,
  FIsKeepAlive: false,
  FOrderNum: 0
});

// 表单验证规则
const rules = reactive({
  FTitle: [{ required: true, message: "请输入路由标题", trigger: "blur" }],
  FName: [{ required: true, message: "请输入路由名称", trigger: "blur" }],
  FPath: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  FComponent: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  FOrderNum: [{ required: true, message: "请输入显示顺序", trigger: "blur" }]
});

// 表格配置项
const columns = reactive<ColumnProps<Route.RouteItem>[]>([
  {
    prop: "FTitle",
    label: "标题",
    width: 150
  },
  {
    prop: "FId",
    label: "id",
    width: 150
  },
  {
    prop: "FPath",
    label: "路径",
    width: 150
  },
  {
    prop: "FName",
    label: "名称",
    width: 150
  },
  {
    prop: "FComponent",
    label: "组件路径",
    width: 150
  },
  {
    prop: "FRedirect",
    label: "重定向",
    width: 150
  },
  {
    prop: "FIcon",
    label: "icon",
    width: 150
  },
  {
    prop: "FIsLink",
    label: "外链",
    width: 150
  },
  {
    prop: "FIsHide",
    label: "是否隐藏",
    width: 100,
    render: scope => {
      return <el-tag type={scope.row.FIsHide ? "danger" : "success"}>{scope.row.FIsHide ? "隐藏" : "显示"}</el-tag>;
    }
  },
  {
    prop: "FIsFull",
    label: "是否全屏",
    width: 100,
    render: scope => {
      return <el-tag type={scope.row.FIsFull ? "success" : "info"}>{scope.row.FIsFull ? "全屏" : "正常"}</el-tag>;
    }
  },
  {
    prop: "FIsAffix",
    label: "是否固定",
    width: 100,
    render: scope => {
      return <el-tag type={scope.row.FIsAffix ? "success" : "info"}>{scope.row.FIsAffix ? "固定" : "不固定"}</el-tag>;
    }
  },
  {
    prop: "FIsKeepAlive",
    label: "是否缓存",
    width: 100,
    render: scope => {
      return <el-tag type={scope.row.FIsKeepAlive ? "success" : "info"}>{scope.row.FIsKeepAlive ? "缓存" : "不缓存"}</el-tag>;
    }
  },
  {
    prop: "FOrderNum",
    label: "顺序",
    width: 80
  },
  { prop: "operation", label: "操作", width: 160, fixed: "right" }
]);

// 打开抽屉
const openDrawer = async (type: "add" | "edit", rowData?: Route.RouteItem) => {
  await getRouteTreeData();

  actionType.value = type;
  drawerTitle.value = type === "add" ? "新增路由" : "编辑路由";

  if (type === "edit" && rowData) {
    Object.assign(formData, rowData);
  } else {
    resetForm();
  }

  drawerVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    FParentId: null,
    FTitle: "",
    FName: "",
    FPath: "",
    FComponent: "",
    FRedirect: null,
    FIcon: "",
    FIsLink: "",
    FIsHide: false,
    FIsFull: false,
    FIsAffix: false,
    FIsKeepAlive: false,
    FOrderNum: 0
  });
};

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate();

  try {
    if (actionType.value === "add") {
      await addRouteApi(formData);
      ElMessage.success("新增成功");
    } else {
      await updateRouteApi(formData);
      ElMessage.success("更新成功");
    }

    drawerVisible.value = false;
    proTable.value?.getTableList();
  } catch (error) {
    console.error(error);
  }
};

// 删除路由
const handleDelete = (row: Route.RouteItem) => {
  ElMessageBox.confirm(`确定删除路由 "${row.FTitle}" 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteRouteApi({ FId: row.FId });
        ElMessage.success("删除成功");
        proTable.value?.getTableList();
      } catch (error) {
        console.error(error);
      }
    })
    .catch(error => {
      throw new Error(error);
    });
};

// 获取路由树形数据
const getRouteTreeData = async () => {
  try {
    const res = await getRouteListApi();
    routeTreeData.value = res.data || [];
  } catch (error) {
    console.error(error);
  }
};
</script>

<style scoped>
.main-box {
  width: 100%;
  height: 100%;
  padding: 20px;
}
.table-box {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
</style>
